package com.ido.otaclient.main;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;

import com.google.gson.Gson;
import com.ido.otaclient.DeviceManagerModel;
import com.ido.otaclient.R;
import com.ido.otaclient.UploadConfigPreference;
import com.ido.otaclient.adapter.SimpleFragmentStatePagerAdapter;
import com.ido.otaclient.api.OkhttpUtil;
import com.ido.otaclient.base.ApiConstant;
import com.ido.otaclient.base.BaseActivity;
import com.ido.otaclient.base.Constant;
import com.ido.otaclient.base.IDLog;
import com.ido.otaclient.device.DeviceFragment;
import com.ido.otaclient.dialog.WaitingDialog;
import com.ido.otaclient.font.FontActivity;
import com.ido.otaclient.font.FontPerfence;
import com.ido.otaclient.fontb.FontBActivity;
import com.ido.otaclient.fontb.FontBPerference;
import com.ido.otaclient.four.FourToOneActivity;
import com.ido.otaclient.four.FourToOnePreference;
import com.ido.otaclient.home.HomeFragment;
import com.ido.otaclient.module.UploadConfig;
import com.ido.otaclient.module.Veneer;
import com.ido.otaclient.nordic.NordicActivity;
import com.ido.otaclient.nordic.NordicConfigPerfence;
import com.ido.otaclient.realtk.RealtkActivity;
import com.ido.otaclient.realtk.RealtkConfigPerfence;
import com.ido.otaclient.three.ThreeToOneActivity;
import com.ido.otaclient.three.ThreeToOnePerfence;
import com.ido.otaclient.two.TwoToOneActivity;
import com.ido.otaclient.two.TwoToOnePerfence;
import com.ido.otaclient.util.AppExecutors;
import com.ido.otaclient.util.ToastUtils;
import com.ido.otaclient.view.SetUpUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Copyright (c) 2019 深圳市爱都科技有限公司. All rights reserved.
 *
 * @Author: xyb
 * @CreateDate: 2020-02-11 17:13
 * @description
 */
public class MainActivity extends BaseActivity implements MainContract.View{

    private HomeFragment mHomeFragment;
    private DeviceFragment mDeviceFragment;

    /**
     * 侧滑栏
     */
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;

    /**
     * nordic 升级
     */
    @BindView(R.id.tv_nordic)
    TextView mTvNordic;

    /**
     * realtk升级
     */
    @BindView(R.id.tv_realtk)
    TextView mTvRealtk;
    /**
     * 四合一升级
     */
    @BindView(R.id.tv_four_to_one)
    TextView mTvFourToOne;
    /**
     * page页
     */
    @BindView(R.id.customer_viewpage)
    CustomViewPager mClipViewPage;

    /**
     * 主界面之间的通信
     */
    private DeviceManagerModel mDeviceManagerModel;
    /**
     * 设备集合
     */
    private List<Veneer> mVeneerList = new ArrayList<>();
    /**
     * 权限申请
     */
    private List<String> permissionList = new ArrayList<>();

    private int requestPermissonCount = 0;

    private final int SDK_PERMISSION_REQUEST = 127;

    /**
     * 除端口号后面一位的ip
     */
    private String mBaseUrl = "";

    /**
     * 遍历ip的次数
     */
    private int mCountIp = 0;

    /**
     * 轮询端口的次数
     */
    private int mCountPort= 0;
    /**
     * 异步操作处理
     */
    //private Handler mHandler = new Handler(Looper.getMainLooper());

    private SimpleFragmentStatePagerAdapter mPageAdapter;
    private List<Fragment> mFragmentList;

    @BindView(R.id.main_tab)
    RadioGroup mClipTab;
    /**
     * okhttp 访问网络的类
     */
    private OkhttpUtil okhttpUtil;

    private MainContract.Presenter mPresenter;

    /**
     * 是否配置
     */
    private boolean mIsConfig;

    /**
     * 是否是升级完成
     */
    private boolean mIsUpgradeComplete = true;

    /**
     * 单板列表
     */
    private static final String EXTRA_VENEER_LIST = "veneer_list";



    @Override
    protected void onCreateTask(Bundle savedInstanceState) {
        super.onCreateTask(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Intent intent = new Intent(this, HttpService.class);
        //startService(intent);

        /**
         * 启动服务
         */
        //NIOHttpServer nioHttpServer = NIOHttpServer.getInstance();
        //nioHttpServer.startServer();
        //设置权限
        initPermision();
        initData();
        initFragment();
        initViewPager();
        initListener();
        initDrawerLayout();
    }

    private void initFragment() {
        mHomeFragment = HomeFragment.newInstance();
        mDeviceFragment = DeviceFragment.newInstance();

        mFragmentList = new ArrayList<>();
        mFragmentList.add(mHomeFragment);
        mFragmentList.add(mDeviceFragment);
    }

    private void initViewPager() {
        mClipViewPage.setScanScroll(false);
        mPageAdapter = new SimpleFragmentStatePagerAdapter(getSupportFragmentManager(),
                mFragmentList);
        //设置adpter
        mClipViewPage.setAdapter(mPageAdapter);
        //组合标签tab和页面
        SetUpUtil.setUpWithRadioGroupAndViewPager(mClipTab, mClipViewPage);
        //选中第一个标签
        mClipTab.check(mClipTab.getChildAt(0).getId());

        mClipViewPage.setOffscreenPageLimit(2);
    }




    private void initPermision() {
        permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        permissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        permissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        permissionList.add(Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
        permissionList.add(Manifest.permission.BLUETOOTH_ADMIN);
        permissionList.add(Manifest.permission.BLUETOOTH);
        getPermission();
    }


    @Override
    protected void onRestartTask() {
        super.onRestartTask();
        IDLog.d(TAG, "onRestartTask: ");
        drawerLayout.closeDrawers();

    }

    private void getPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && requestPermissonCount < 5) {
            if (permissionList.size() != 0) {
                requestPermissonCount++;
                requestPermissions(permissionList.toArray(new String[permissionList.size()]),
                        SDK_PERMISSION_REQUEST);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == SDK_PERMISSION_REQUEST) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    permissionList.remove(permissions[i]);
                }
            }
            getPermission();
        }
    }

    private void initData() {

        mDeviceManagerModel = ViewModelProviders.of(this).get(DeviceManagerModel.class);

        mDeviceManagerModel.getVeneerModelLiveData().observe(this,veneers -> {
            mVeneerList = veneers;
        });

        mPresenter = new MainPersenter(this);
        mPresenter.getCurrentIp();
        //获取ip
        getVeneer();
    }




    /**
     * 获取单板列表
     */
    private void getVeneer() {
        //获取列表
        mCountIp = 0;
        mCountPort = 0;
        mVeneerList = new ArrayList<>();
        if(TextUtils.isEmpty(mBaseUrl)){
            showMessage("获取当前ip失败，请重启app后再次尝试");
            return;
        }
        WaitingDialog.showDialog(MainActivity.this);
       okhttpUtil = OkhttpUtil.getInstance();
       //监听第一个端口
        for (int i = 0; i <= 255; i++) {
            String ip = mBaseUrl + i + ":" + Constant.HTTP_PORT
                    + "/" + ApiConstant.METHOD_VENEER_LIST;
            IDLog.d(TAG, "getVeneer: " + ip);
            getVeneerByIp(ip);
        }
        //监听第二个端口
        /*for (int i = 0; i <= 255; i++) {
            String ip = mBaseUrl + i + ":" + Constant.HTTP_PORT_TWO
                    + "/" + ApiConstant.METHOD_VENEER_LIST;
            IDLog.d(TAG, "getVeneer: " + ip);
            getVeneerByIp(ip);
        }*/
        //监听第三个端口
        /*for (int i = 0; i <= 255; i++) {
            String ip = mBaseUrl + i + ":" + Constant.HTTP_PORT_THREE
                    + "/" + ApiConstant.METHOD_VENEER_LIST;
            IDLog.d(TAG, "getVeneer: " + ip);
            getVeneerByIp(ip);
        }*/

        /*String ip = mBaseUrl + 176 + ":" + Constant.HTTP_PORT
                + "/" + ApiConstant.METHOD_VENEER_LIST;
        IDLog.d(TAG, "getVeneer: " + ip);
        getVeneerByIp(ip);*/
        /**
         * 访问的次数不是叠加的所以增加一个10秒的结束时间
         */
        /*mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                *//**
                 *要执行的操作
                 *//*
                WaitingDialog.hideDialog();
                mDeviceManagerModel.getVeneerModelLiveData().postValue(mVeneerList);
            }
        }, 1000*10);//10秒后执行Runnable中的run方法*/
    }

    /**
     * 获取第二个端口
     */
    private void getSecondPort(){
        for (int i = 0; i <= 255; i++) {
            String ip = mBaseUrl + i + ":" + Constant.HTTP_PORT_TWO
                    + "/" + ApiConstant.METHOD_VENEER_LIST;
            IDLog.d(TAG, "getVeneer: " + ip);
            getVeneerByIp(ip);
        }
    }

    /**
     * 获得第三个端口的数据
     */
    private void getThirdPort(){
        for (int i = 0; i <= 255; i++) {
            String ip = mBaseUrl + i + ":" + Constant.HTTP_PORT_THREE
                    + "/" + ApiConstant.METHOD_VENEER_LIST;
            IDLog.d(TAG, "getVeneer: " + ip);
            getVeneerByIp(ip);
        }
    }


    /**
     * 访问网络
     *
     * @param s
     */
    private void getVeneerByIp(String s) {
        okhttpUtil.getSyn(s, new OkhttpUtil.OkhttpCallback() {
            @Override
            public void onSuccess(String success) {
                //到达255次后跳转到设备列表界面
                AppExecutors.globalAppExecutors().mainThread().execute(() -> setVeneerList(success));
                AppExecutors.globalAppExecutors().mainThread().execute(() -> scanComplete());

            }

            @Override
            public void onFailed(String message) {
                AppExecutors.globalAppExecutors().mainThread().execute(new Runnable() {
                    @Override
                    public void run() {
                        scanComplete();
                    }
                });
            }
        });
    }

    /**
     * 设置单板集合
     */
    private void setVeneerList(String success) {
        IDLog.d(TAG, "setVeneerList: " + success);
        Gson gson = new Gson();
        Veneer veneer = gson.fromJson(success,Veneer.class);
        mVeneerList.add(veneer);
    }

    /**
     * 扫描结束
     */
    private void scanComplete() {
        mCountIp++;
        if (mCountIp == 256) {
            getSecondPort();
        }
        else if(mCountIp == 256 *2){
            getThirdPort();
        } else if(mCountIp == 256 * 3) {
            WaitingDialog.hideDialog();
            mDeviceManagerModel.getVeneerModelLiveData().postValue(mVeneerList);
        }
    }



    private void initDrawerLayout() {
        //注意：初始化的是drawerlayout整个大布局，不是初始化抽屉的那个id
        drawerLayout = (DrawerLayout) super.findViewById(R.id.drawer_layout);
        drawerLayout.setScrimColor(Color.TRANSPARENT);
        //drawerLayout.closeDrawers();
        //禁止手势滑动
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        //打开侧栏
        //drawerLayout.openDrawer(GravityCompat.END);
        //关闭侧栏
        drawerLayout.closeDrawers();
    }

    private void initListener() {
        /**
         * 配置监听
         */
        mHomeFragment.setOnItemListener((isConfig,isUpgradeComplete) -> {
            mIsConfig = isConfig;
            mIsUpgradeComplete = isUpgradeComplete;
            //打开侧栏
            drawerLayout.openDrawer(GravityCompat.END);
        });

    }

    @OnClick(R.id.tv_nordic)
    public void toNordic(View view){
        UploadConfigPreference uploadConfigPreference = UploadConfigPreference.getInstance();
        UploadConfig uploadConfig = UploadConfigPreference.getInstance().getUploadConfig();
        IDLog.d(TAG, "toNordic: "+ mIsConfig +","+mIsUpgradeComplete +","+ uploadConfig.getTaskName());
        if(mIsConfig){
            //正在升级中且升级类型为同一种类型则出弹框
            if(!mIsUpgradeComplete && uploadConfig.getTaskName().equals(Constant.TASK_NAME_NORDIC)){
                mHomeFragment.showConfirmCancelTask();
                //关闭侧栏
                drawerLayout.closeDrawers();
            }else {
                NordicActivity.startActivity(MainActivity.this,mVeneerList);
            }
        }else {
            NordicConfigPerfence nordicConfigPerfence = NordicConfigPerfence.getInstance();
            if(TextUtils.isEmpty(nordicConfigPerfence.getNordicConfig().getTaskName())){
                NordicActivity.startActivity(MainActivity.this,mVeneerList);
            }else {
                drawerLayout.closeDrawers();
                uploadConfig = new UploadConfig();
                uploadConfig.setTaskName(Constant.TASK_NAME_NORDIC);
                uploadConfigPreference.saveUploadConfig(uploadConfig);
                mHomeFragment.startTask(Constant.TASK_NAME_NORDIC);
            }
        }
    }


    @OnClick(R.id.tv_realtk)
    public void toRealtk(View view){
        UploadConfigPreference uploadConfigPreference = UploadConfigPreference.getInstance();
        UploadConfig uploadConfig = UploadConfigPreference.getInstance().getUploadConfig();
        IDLog.d(TAG, "toFourToOne: "+ mIsConfig +","+mIsUpgradeComplete +","+ uploadConfig.getTaskName());
        if(mIsConfig){
            //正在升级中且升级类型为同一种类型则出弹框
            if(!mIsUpgradeComplete && uploadConfig.getTaskName().equals(Constant.TASK_NAME_REALTK)){
                mHomeFragment.showConfirmCancelTask();
                //关闭侧栏
                drawerLayout.closeDrawers();
            }else {
                RealtkActivity.startActivity(MainActivity.this,mVeneerList);
            }
        }else {
            RealtkConfigPerfence realtkConfigPerfence = RealtkConfigPerfence.getInstance();
            if(TextUtils.isEmpty(realtkConfigPerfence.getRealtkConfig().getTaskName())){
                RealtkActivity.startActivity(MainActivity.this,mVeneerList);
            }else {
                drawerLayout.closeDrawers();
                uploadConfig = new UploadConfig();
                uploadConfig.setTaskName(Constant.TASK_NAME_REALTK);
                uploadConfigPreference.saveUploadConfig(uploadConfig);
                mHomeFragment.startTask(Constant.TASK_NAME_REALTK);
            }
        }
    }

    @OnClick(R.id.tv_four_to_one)
    public void toFourToOne(View view){
        UploadConfigPreference uploadConfigPreference = UploadConfigPreference.getInstance();
        UploadConfig uploadConfig = UploadConfigPreference.getInstance().getUploadConfig();
        IDLog.d(TAG, "toFourToOne: "+ mIsConfig +","+mIsUpgradeComplete +","+ uploadConfig.getTaskName());
        if(mIsConfig){
            //正在升级中且升级类型为同一种类型则出弹框
            if(!mIsUpgradeComplete && uploadConfig.getTaskName().equals(Constant.TASK_NAME_FOUR_TO_ONE)){
                mHomeFragment.showConfirmCancelTask();
                //关闭侧栏
                drawerLayout.closeDrawers();
            }else {
                FourToOneActivity.startActivity(MainActivity.this,mVeneerList);
            }
        }else {
            FourToOnePreference fourToOnePreference = FourToOnePreference.getInstance();
            if(TextUtils.isEmpty(fourToOnePreference.getUploadConfig().getTaskName())){
                FourToOneActivity.startActivity(MainActivity.this,mVeneerList);
            }else {
                drawerLayout.closeDrawers();
                uploadConfig = new UploadConfig();
                uploadConfig.setTaskName(Constant.TASK_NAME_FOUR_TO_ONE);
                uploadConfigPreference.saveUploadConfig(uploadConfig);
                mHomeFragment.startTask(Constant.TASK_NAME_FOUR_TO_ONE);
            }
        }
    }

    @OnClick(R.id.tv_two_to_one)
    public void toTwoToOne(View view){
        UploadConfigPreference uploadConfigPreference = UploadConfigPreference.getInstance();
        UploadConfig uploadConfig = UploadConfigPreference.getInstance().getUploadConfig();
        IDLog.d(TAG, "toTwoToOne: "+ mIsConfig +","+mIsUpgradeComplete +","+ uploadConfig.getTaskName());
        if(mIsConfig){
            //正在升级中且升级类型为同一种类型则出弹框
            if(!mIsUpgradeComplete && uploadConfig.getTaskName().equals(Constant.TASK_NAME_TWO_TO_ONE)){
                mHomeFragment.showConfirmCancelTask();
                //关闭侧栏
                drawerLayout.closeDrawers();
            }else {
                TwoToOneActivity.startActivity(MainActivity.this,mVeneerList);
            }
        }else {
            TwoToOnePerfence twoToOnePerfence = TwoToOnePerfence.getInstance();
            if(TextUtils.isEmpty(twoToOnePerfence.getTwoToOneConfig().getTaskName())){
                NordicActivity.startActivity(MainActivity.this,mVeneerList);
            }else {
                drawerLayout.closeDrawers();
                uploadConfig = new UploadConfig();
                uploadConfig.setTaskName(Constant.TASK_NAME_TWO_TO_ONE);
                uploadConfigPreference.saveUploadConfig(uploadConfig);
                mHomeFragment.startTask(Constant.TASK_NAME_TWO_TO_ONE);
            }
        }
    }

    @OnClick(R.id.tv_three_to_one)
    public void toThreeToOne(View viwe){
        UploadConfigPreference uploadConfigPreference = UploadConfigPreference.getInstance();
        UploadConfig uploadConfig = UploadConfigPreference.getInstance().getUploadConfig();
        IDLog.d(TAG, "toTwoToOne: "+ mIsConfig +","+mIsUpgradeComplete +","+ uploadConfig.getTaskName());
        if(mIsConfig){
            //正在升级中且升级类型为同一种类型则出弹框
            if(!mIsUpgradeComplete && uploadConfig.getTaskName().equals(Constant.TASK_NAME_THREE_TO_ONE)){
                mHomeFragment.showConfirmCancelTask();
                //关闭侧栏
                drawerLayout.closeDrawers();
            }else {
                ThreeToOneActivity.startActivity(MainActivity.this,mVeneerList);
            }
        }else {
            ThreeToOnePerfence threeToOnePerfence = ThreeToOnePerfence.getInstance();
            if(TextUtils.isEmpty(threeToOnePerfence.getThreeToOneConfig().getTaskName())){
                ThreeToOneActivity.startActivity(MainActivity.this,mVeneerList);
            }else {
                drawerLayout.closeDrawers();
                uploadConfig = new UploadConfig();
                uploadConfig.setTaskName(Constant.TASK_NAME_THREE_TO_ONE);
                uploadConfigPreference.saveUploadConfig(uploadConfig);
                mHomeFragment.startTask(Constant.TASK_NAME_THREE_TO_ONE);
            }
        }
    }

    @OnClick(R.id.tv_font_library)
    public void toFontLibrary(View view){
        UploadConfigPreference uploadConfigPreference = UploadConfigPreference.getInstance();
        UploadConfig uploadConfig = UploadConfigPreference.getInstance().getUploadConfig();
        IDLog.d(TAG, "toFontLibrary: "+ mIsConfig +","+mIsUpgradeComplete +","+ uploadConfig.getTaskName());
        if(mIsConfig){
            //正在升级中且升级类型为同一种类型则出弹框
            if(!mIsUpgradeComplete && uploadConfig.getTaskName().equals(Constant.TASK_NAME_FONT)){
                mHomeFragment.showConfirmCancelTask();
                //关闭侧栏
                drawerLayout.closeDrawers();
            }else {
                FontActivity.startActivity(MainActivity.this,mVeneerList);
            }
        }else {
            FontPerfence fontPerfence = FontPerfence.getInstance();
            if(TextUtils.isEmpty(fontPerfence.getFontConfig().getTaskName())){
                FontActivity.startActivity(MainActivity.this,mVeneerList);
            }else {
                drawerLayout.closeDrawers();
                uploadConfig = new UploadConfig();
                uploadConfig.setTaskName(Constant.TASK_NAME_FONT);
                uploadConfigPreference.saveUploadConfig(uploadConfig);
                mHomeFragment.startTask(Constant.TASK_NAME_FONT);
            }
        }
    }

    @OnClick(R.id.tv_b_font_library)
    public void toFontBLibrary(View view){
        UploadConfigPreference uploadConfigPreference = UploadConfigPreference.getInstance();
        UploadConfig uploadConfig = UploadConfigPreference.getInstance().getUploadConfig();
        IDLog.d(TAG, "toFontBLibrary: "+ mIsConfig +","+mIsUpgradeComplete +","+ uploadConfig.getTaskName());
        if(mIsConfig){
            //正在升级中且升级类型为同一种类型则出弹框
            if(!mIsUpgradeComplete && uploadConfig.getTaskName().equals(Constant.TASK_NAME_FONT_B)){
                mHomeFragment.showConfirmCancelTask();
                //关闭侧栏
                drawerLayout.closeDrawers();
            }else {
                FontBActivity.startActivity(MainActivity.this,mVeneerList);
            }
        }else {
            FontBPerference fontBPerference = FontBPerference.getInstance();
            if(TextUtils.isEmpty(fontBPerference.getFontBConfig().getTaskName())){
                FontBActivity.startActivity(MainActivity.this,mVeneerList);
            }else {
                drawerLayout.closeDrawers();
                uploadConfig = new UploadConfig();
                uploadConfig.setTaskName(Constant.TASK_NAME_FONT_B);
                uploadConfigPreference.saveUploadConfig(uploadConfig);
                mHomeFragment.startTask(Constant.TASK_NAME_FONT_B);
            }
        }
    }

    @Override
    protected void onDestroyTask() {
        super.onDestroyTask();
        mDeviceManagerModel.stopTimer();

    }

    @Override
    public void showLoading() {
        WaitingDialog.showDialog(MainActivity.this);
    }

    @Override
    public void hideLoading() {
        WaitingDialog.hideDialog();
    }

    @Override
    public void showMessage(String message) {
        ToastUtils.show(message);
    }

    @Override
    public void setBaseUrl(String url) {
        mBaseUrl = url;
    }

    @Override
    public String getBaseUrl() {
        return mBaseUrl;
    }

    @Override
    public void setPresenter(@NonNull MainContract.Presenter presenter) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == Constant.REQUEST_CODE_LIST && resultCode == Constant.REQUEST_CODE_LIST){
            Bundle bundle = data.getExtras();
            List<Veneer> veneerList = (List<Veneer>) bundle.getSerializable(EXTRA_VENEER_LIST);
            for(Veneer veneer : veneerList){
                IDLog.d(TAG, "onActivityResult: " + veneer.toString());
            }
            mDeviceManagerModel.getVeneerModelLiveData().setValue(veneerList);
        }
    }
}
